<script setup lang="ts">
// import { RouterLink, RouterView } from 'vue-router'

 
// import SerialCommon from './serial';

</script>
<script lang="ts">
import SerialCommon from './serial';

let filters = [{ usbVendorId: 0x1a86, usbProductId: 0x7523 }]
let sc = new SerialCommon.SerialCommon();

export default {
  data() {
    return {
      text: '',
      state: false,
      received: ''
    }
  },

  async mounted() {
    sc.onmessage = this.onmessage;
    sc.onconnect = () => {
      this.state = sc.state;
    };
    sc.ondisconnect = () => {
      this.state = sc.state;
    }

    this.autoConnect();
  },
  methods: {
    onmessage(data: Uint8Array) {
      // this.received = new TextDecoder().decode(data);
      this.received = data.toString();
      console.log(this.received)
    },
    async autoConnect() {
      this.state = await sc.connect();
    },
    async requset() {
      await sc.request();
      this.state = await sc.open();
    },
    async open() {
      this.state = await sc.connect();
    },

    async send() {
      const data = new TextEncoder().encode(this.text + '\r\n')
      this.state = await sc.write(data);
    },
    async closeUart() {
      this.state = !await sc.close();
    }
  }
}
</script>

<template>
  <header>
    <div class="wrapper">
      <el-col>
        <el-row>
          <el-button v-if="!state" @click="requset" type="primary">授权串口</el-button>
          <el-button v-if="!state" @click="open" type="primary">连接串口</el-button>
          <el-button v-else @click="closeUart" type="success">关闭串口</el-button>
        </el-row>
        <el-row v-if="state">
          <el-input v-model="text" placeholder="Please input" clearable />
          <el-button @click="send">发送</el-button>
        </el-row>
      </el-col>
    </div>
  </header>
  <div>
    <p>AT指令接收的数据</p>
    <el-input v-model="received" :rows="4" type="textarea" clearable disabled />
  </div>
</template>

<style scoped>
header {
  line-height: 1.5;
  max-height: 100vh;
}


.wrapper {
  width: 280px;
}

nav {
  width: 100%;
  font-size: 12px;
  text-align: center;
  margin-top: 2rem;
}

@media (min-width: 1024px) {
  header {
    display: flex;
    place-items: center;
    padding-right: calc(var(--section-gap) / 2);
  }

  nav {
    text-align: left;
    margin-left: -1rem;
    font-size: 1rem;

    padding: 1rem 0;
    margin-top: 1rem;
  }
}
</style>
